<?php

/**
 * contact : 刘经理 19326416371
 * company : 版权所属 四川北星惯牌科技有限公司
 **/

namespace app\admin\command\Project;

use app\common\constant\Constant;
use app\common\library\Wechat;
use app\common\manager\GroupManager;
use app\common\manager\StatisticsManager;
use app\common\model\Store;
use app\common\model\NumberStatistics;
use app\common\model\StoreAccount;
use app\common\model\UserTeam;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\Db;
use think\Exception;

class Team extends Command
{
    protected $model = null;

    protected function configure()
    {
        $this->setName('team')
            ->setDescription('task');
        //要执行的controller必须一样，不适用模糊查询
    }

    protected function execute(Input $input, Output $output)
    {
        $redis = new \Redis();
        $config = config('redis');
        $redis->pconnect($config['host'],$config['port']);

        $userTeamModel = new UserTeam();
        $wechat = new Wechat();
        if ($config['password']){
            $redis->auth($config['password']);
        }
        while (true){

            $data = $redis->hGetAll(Constant::getHashAllTeamKey($config['prefix']));
            $count = count($data);
            if ($data){
                foreach ($data as $k=>$v){
                    Db::startTrans();
                    try {
                        $v = json_decode($v,true);
                        if ($v['start_date'] < (time()-60) ){
                            $info = \app\common\model\Team::where('t_id',$v['t_id'])->find();
                            if ($info['number_people'] > $info['join_number']){
                                try {
                                    $result = GroupManager::cancelGroupBySystem($info['t_id'],false);
                                    if ($result['code']!=GroupManager::$successCode){
                                        throw new \Exception($result['message']);
                                    }else{
                                        $redis->hDel(Constant::getHashAllTeamKey($config['prefix']),$info['t_id']);

                                    }
                                }catch (Exception $e){
                                    echo $e->getMessage().$e->getLine().$e->getFile();
                                }
                            }else{
                                if ($v['end_date'] < time()){
                                    $userTeamInfo = $userTeamModel->alias('ut')
                                        ->join('user u','u.id=ut.user_id','inner')
                                        ->join('team t','t.t_id=ut.team','inner')
                                        ->where('ut.team',$v['t_id'])->where('ut.pay_state',UserTeam::PAY_STATUS_SUCCESS)
                                        ->field('ut.*,u.open_id,t.start_date,t.end_date')
                                        ->select();
                                    if ($userTeamInfo){
                                        foreach ($userTeamInfo as $utv){
                                            if ($utv->open_id){
                                                $params['title'] = $utv->title ?? '组队消息';
                                                $params['start_date'] = date('Y-m-d H:i:s',$utv->start_date);
                                                $params['end_date'] = date('Y-m-d H:i:s',$utv->end_date);
                                                $params['notice'] = '当前组队已结束';
                                                $wechat->publishMsg($utv->open_id,$params,Wechat::TEMPLATE_ID_END,config('wechat.team_invite_page'));
                                            }
                                        }
                                    }
                                    //GroupManager::confirmGroup($v['t_id']);
                                    if ($info['store_id']){
                                        StoreAccount::where('store_id',$info['store_id'])->update([
                                            'total_number'=>Db::raw('total_number + 1'),
                                            'team_number'=>Db::raw('team_number + 1'),
                                            'version'=>Db::raw('version + 1'),
                                            'updatetime'=>time(),

                                        ]);

                                        $merchantId = Store::where('id',$info['store_id'])->value('merchant_id');
                                        if ($merchantId){

                                            $result = StatisticsManager::enter($merchantId,$info['store_id'],1,$info['end_date'],NumberStatistics::TYPE_TEAM,StatisticsManager::TYPE_NUMBER,false);
                                            if ($result['code'] != StatisticsManager::$successCode){
                                                throw new Exception($result['message']);
                                            }
                                        }

                                    }
                                    $redis->hDel(Constant::getHashAllTeamKey($config['prefix']),$info['t_id']);
                                }

                            }
                        }
                        Db::commit();
                    }catch (Exception $e){
                        Db::rollback();
                        echo $e->getMessage().$e->getLine();
                    }

                }
            }

            if ($count < 1){
                $redis->del(Constant::getHashAllTeamKey($config['prefix']));
            }

            sleep(10);
        }
    }

}
